<template>
  <header class="bg-white shadow-sm h-16 fixed top-0 left-0 right-0 z-20">
    <div class="container mx-auto px-4 h-full flex items-center justify-between">
      <div class="flex items-center">
        <h1 class="text-2xl font-bold text-blue-800">
          钢铁企业安全生产智能监管平台
        </h1>
      </div>
      <div class="flex items-center space-x-6">
        <!-- 通知公告 -->
        <div class="relative">
          <div
            class="flex items-center space-x-2 cursor-pointer p-2 rounded-lg hover:bg-gray-100 transition-colors duration-200"
            @click.stop="toggleNotificationMenu">
            <div class="relative">
              <!-- 通知徽章 -->
              <div v-if="unreadCount > 0"
                class="absolute -top-1 -right-1 z-20 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center shadow-sm border border-white">
                {{ unreadCount > 99 ? "99+" : unreadCount }}
              </div>
              <div
                class="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center text-blue-600 relative z-10">
                <i class="fas fa-bell"></i>
              </div>
            </div>
            <span class="text-gray-700 text-sm">通知公告</span>
            <i class="fas fa-chevron-down text-gray-500 text-xs transition-transform duration-200"
              :class="{ 'rotate-180': showNotificationMenu }"></i>
          </div>

          <!-- 通知下拉菜单 -->
          <div v-if="showNotificationMenu"
            class="absolute right-0 top-full mt-2 w-80 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50 max-h-96 overflow-y-auto">
            <!-- 通知标题 -->
            <div class="px-4 py-2 border-b border-gray-100">
              <h3 class="font-semibold text-gray-800 flex items-center">
                <i class="fas fa-bell mr-2 text-blue-600"></i>
                通知公告
                <span v-if="unreadCount > 0" class="ml-2 text-xs bg-red-500 text-white px-2 py-1 rounded-full">
                  {{ unreadCount }}条未读
                </span>
              </h3>
            </div>

            <!-- 通知列表 -->
            <div class="max-h-64 overflow-y-auto">
              <div v-for="notification in notifications" :key="notification.id"
                class="px-4 py-3 border-b border-gray-100 last:border-b-0 hover:bg-gray-50 cursor-pointer transition-colors duration-200"
                :class="{ 'bg-blue-50': !notification.isRead }" @click="handleNotificationClick(notification)">
                <div class="flex justify-between items-start mb-1">
                  <span class="font-medium text-sm" :class="notification.isRead ? 'text-gray-700' : 'text-gray-900'
                    ">
                    {{ notification.title }}
                  </span>
                  <span class="text-xs text-gray-500">
                    {{ formatTime(notification.timestamp) }}
                  </span>
                </div>
                <p class="text-xs text-gray-600 line-clamp-2">
                  {{ notification.content }}
                </p>
                <div class="flex justify-between items-center mt-2">
                  <span class="text-xs px-2 py-1 rounded-full" :class="getNotificationTypeClass(notification.type)">
                    {{ getNotificationTypeText(notification.type) }}
                  </span>
                  <div v-if="!notification.isRead" class="w-2 h-2 bg-red-500 rounded-full"></div>
                </div>
              </div>

              <!-- 空状态 -->
              <div v-if="notifications.length === 0" class="px-4 py-8 text-center text-gray-500">
                <i class="fas fa-bell-slash text-3xl mb-2 text-gray-300"></i>
                <p class="text-sm">暂无通知</p>
              </div>
            </div>

            <!-- 底部操作 -->
            <div class="px-4 py-2 border-t border-gray-100 bg-gray-50">
              <div class="flex justify-between items-center">
                <button @click.stop="markAllAsRead" class="text-xs text-blue-600 hover:text-blue-800 flex items-center"
                  :disabled="unreadCount === 0">
                  <i class="fas fa-check-double mr-1"></i>
                  全部已读
                </button>
                <button @click.stop="viewAllNotifications"
                  class="text-xs text-gray-600 hover:text-gray-800 flex items-center">
                  查看全部
                  <i class="fas fa-chevron-right ml-1 text-xs"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 用户信息 -->
        <div class="relative">
          <div
            class="flex items-center space-x-2 cursor-pointer p-2 rounded-lg hover:bg-gray-100 transition-colors duration-200"
            @click.stop="toggleUserMenu">
            <div class="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white">
              <i class="fas fa-user"></i>
            </div>
            <span class="text-gray-700">{{ userName }}</span>
            <i class="fas fa-chevron-down text-gray-500 text-xs transition-transform duration-200"
              :class="{ 'rotate-180': showUserMenu }"></i>
          </div>

          <!-- 用户下拉菜单 -->
          <div v-if="showUserMenu"
            class="absolute right-0 top-full mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
            <div class="user-menu-item logout" @click="handleLogout">
              <i class="fas fa-sign-out-alt mr-3"></i>
              <span>退出登录</span>
            </div>
          </div>
        </div>

        <!-- 点击外部关闭菜单的遮罩层 -->
        <div v-if="showUserMenu || showNotificationMenu" class="fixed inset-0 z-40" @click="closeAllMenus"></div>
      </div>
    </div>
  </header>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      userName: "管理员",
      unreadCount: 0,
      showUserMenu: false,
      showNotificationMenu: false,
      notifications: [],
    };
  },
  mounted() {
    // 从本地存储加载用户信息
    const savedUserInfo = localStorage.getItem("userInfo");
    if (savedUserInfo) {
      try {
        const userInfo = JSON.parse(savedUserInfo);
        this.userName = userInfo.name || "管理员";
      } catch (e) {
        this.userName = "管理员";
      }
    }

    // 加载通知数据
    this.loadNotifications();

    // 监听通知已读事件
    window.addEventListener("notification-read", this.loadNotifications);

    document.addEventListener("click", this.handleClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.handleClickOutside);
    window.removeEventListener("notification-read", this.loadNotifications);
  },
  methods: {
    toggleUserMenu() {
      this.showUserMenu = !this.showUserMenu;
      this.showNotificationMenu = false;
    },
    toggleNotificationMenu() {
      this.showNotificationMenu = !this.showNotificationMenu;
      this.showUserMenu = false;
    },
    closeAllMenus() {
      this.showUserMenu = false;
      this.showNotificationMenu = false;
    },
    handleNotificationClick(notification) {
      // 标记为已读
      if (!notification.isRead) {
        this.markAsRead(notification.id);
      }

      // 根据通知类型处理点击事件
      switch (notification.type) {
        case "system":
          this.$router.push("/system-notice");
          break;
        case "warning":
          this.$router.push("/warning-detail");
          break;
        case "maintenance":
          this.$router.push("/maintenance-info");
          break;
        default:
          this.$router.push("/notifications");
      }

      this.closeAllMenus();
    },
    viewAllNotifications() {
      this.$router.push("/notifications");
      this.closeAllMenus();
    },
    markAsRead(notificationId) {
      const notification = this.notifications.find(
        (n) => n.id === notificationId
      );
      if (notification && !notification.isRead) {
        notification.isRead = true;
        this.saveNotifications();
        this.updateUnreadCount();
      }
    },
    markAllAsRead() {
      this.notifications.forEach((notification) => {
        notification.isRead = true;
      });
      this.saveNotifications();
      this.updateUnreadCount();
      this.closeAllMenus();
    },
    handleProfile() {
      this.closeAllMenus();
      this.$router.push("/profile");
    },
    handleSettings() {
      this.closeAllMenus();
      this.$router.push("/settings");
    },
    handleHelp() {
      this.closeAllMenus();
      this.$router.push("/help");
    },
    handleClickOutside(event) {
      const userInfoElement = event.target.closest(".relative");
      const userMenuElement = event.target.closest(".user-menu-item");
      const notificationElement = event.target.closest(".relative");

      if (
        (this.showUserMenu || this.showNotificationMenu) &&
        !userInfoElement &&
        !userMenuElement &&
        !notificationElement
      ) {
        this.closeAllMenus();
      }
    },
    loadNotifications() {
      const savedNotifications = localStorage.getItem("notifications");
      const userInfo = localStorage.getItem("userInfo");

      // 检查是否有用户信息，如果没有或者用户信息改变，则重置通知
      if (!userInfo || this.shouldResetNotifications(userInfo)) {
        this.createSampleNotifications();
        // 保存当前用户信息用于下次比较
        localStorage.setItem("lastUser", userInfo);
      } else if (savedNotifications) {
        try {
          this.notifications = JSON.parse(savedNotifications);
        } catch (e) {
          this.createSampleNotifications();
        }
      } else {
        this.createSampleNotifications();
      }
      this.updateUnreadCount();
    },
    shouldResetNotifications(currentUserInfo) {
      const lastUser = localStorage.getItem("lastUser");
      return lastUser !== currentUserInfo;
    },
    createSampleNotifications() {
      // 创建测试通知数据 - 每次都是3个未读，2个已读
      this.notifications = [
        {
          id: 1,
          title: "系统通知",
          content:
            "欢迎使用钢铁企业安全生产智能监管平台，系统已升级至最新版本V2.1.0",
          timestamp: new Date().toISOString(),
          type: "system",
          isRead: false,
        },
        {
          id: 2,
          title: "安全预警",
          content: "检测到3号高炉温度异常，请及时检查处理",
          timestamp: new Date(Date.now() - 3600000).toISOString(),
          type: "warning",
          isRead: false,
        },
        {
          id: 3,
          title: "维护通知",
          content: "系统将于今晚22:00-24:00进行例行维护，期间可能短暂无法访问",
          timestamp: new Date(Date.now() - 7200000).toISOString(),
          type: "maintenance",
          isRead: true,
        },
        {
          id: 4,
          title: "数据更新",
          content: "安全生产数据已完成同步更新，请查看最新统计报告",
          timestamp: new Date(Date.now() - 10800000).toISOString(),
          type: "system",
          isRead: false,
        },
        {
          id: 5,
          title: "培训通知",
          content: "本周五下午14:00将举行安全生产培训，请相关人员准时参加",
          timestamp: new Date(Date.now() - 86400000).toISOString(),
          type: "system",
          isRead: true,
        },
      ];
      this.saveNotifications();
    },
    handleLogout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        localStorage.removeItem("token");
        localStorage.removeItem("userInfo");
        // 跳转到登录页面
        this.$router.push("/login");

        this.$message({
          type: 'success',
          message: '退出成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退出'
        });
      });

      this.closeAllMenus();
    },
    saveNotifications() {
      localStorage.setItem("notifications", JSON.stringify(this.notifications));
    },
    updateUnreadCount() {
      this.unreadCount = this.notifications.filter((n) => !n.isRead).length;
      localStorage.setItem(
        "unreadNotificationCount",
        this.unreadCount.toString()
      );
    },
    formatTime(timestamp) {
      const now = new Date();
      const time = new Date(timestamp);
      const diff = now - time;

      if (diff < 60000) {
        // 1分钟内
        return "刚刚";
      } else if (diff < 3600000) {
        // 1小时内
        return Math.floor(diff / 60000) + "分钟前";
      } else if (diff < 86400000) {
        // 24小时内
        return Math.floor(diff / 3600000) + "小时前";
      } else if (diff < 604800000) {
        // 7天内
        return Math.floor(diff / 86400000) + "天前";
      } else {
        return time.toLocaleDateString();
      }
    },
    getNotificationTypeClass(type) {
      const classes = {
        system: "bg-blue-100 text-blue-800",
        warning: "bg-red-100 text-red-800",
        maintenance: "bg-yellow-100 text-yellow-800",
      };
      return classes[type] || "bg-gray-100 text-gray-800";
    },
    getNotificationTypeText(type) {
      const texts = {
        system: "系统",
        warning: "预警",
        maintenance: "维护",
      };
      return texts[type] || "通知";
    },
  },
};
</script>

<style scoped>
.user-menu-item {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  color: #4a5568;
  font-size: 14px;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
}

.user-menu-item:hover {
  background-color: #f7fafc;
  color: #2d3748;
}

.user-menu-item.logout {
  color: #e53e3e;
}

.user-menu-item.logout:hover {
  background-color: #fed7d7;
  color: #c53030;
}

.rotate-180 {
  transform: rotate(180deg);
}

/* 文本截断 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 滚动条样式 */
.max-h-64::-webkit-scrollbar {
  width: 4px;
}

.max-h-64::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.max-h-64::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.max-h-64::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
